package middleware

import (
	"context"
	"net/http"
	"strings"

	"github.com/golang-jwt/jwt/v5"
	"skedule-backend/utils"
)

// JWTMiddleware JWT认证中间件
func JWTMiddleware(jwtSecret string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// 获取Authorization头
			authHeader := r.Header.Get("Authorization")
			if authHeader == "" {
				http.Error(w, utils.T("middleware.auth.header.missing"), http.StatusUnauthorized)
				return
			}

			// 检查Bearer前缀
			if !strings.HasPrefix(authHeader, "Bearer ") {
				http.Error(w, utils.T("middleware.auth.format.invalid"), http.StatusUnauthorized)
				return
			}

			// 提取token
			tokenString := strings.TrimPrefix(authHeader, "Bearer ")
			
			// 验证token
			token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
				if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
					return nil, jwt.ErrSignatureInvalid
				}
				return []byte(jwtSecret), nil
			})

			if err != nil || !token.Valid {
				http.Error(w, utils.T("middleware.auth.token.invalid"), http.StatusUnauthorized)
				return
			}

			// 从token中提取用户信息
			if claims, ok := token.Claims.(jwt.MapClaims); ok {
				if username, exists := claims["username"].(string); exists {
					// 将用户名添加到上下文中
					ctx := context.WithValue(r.Context(), "username", username)
					r = r.WithContext(ctx)
				}
			}

			next.ServeHTTP(w, r)
		})
	}
}

// CORS中间件
func CORS(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		next.ServeHTTP(w, r)
	})
} 